<template>
  <div class="personal-space">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
        <el-card class="avatar-card">
          <div class="avatar-container">
            <el-upload
              class="avatar-uploader"
              action="/api/user/upload"
              :headers="{ Authorization: userStore.token }"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-error="handleAvatarError"
              :on-progress="handleAvatarProgress"
            >
              <div class="avatar-wrapper">
                <el-avatar
                  :size="120"
                  :src="avatarUrl"
                  class="user-avatar"
                  @error="() => { console.error('头像加载失败，使用默认头像'); avatarUrl = defaultAvatar }"
                >
                  <el-icon><UserFilled /></el-icon>
                </el-avatar>
                <div class="avatar-mask" v-if="!isUploading">
                  <el-icon><EditPen /></el-icon>
                  <span>更换头像</span>
                </div>
                <el-progress
                  v-if="isUploading"
                  type="circle"
                  :percentage="uploadProgress"
                  class="upload-progress"
                />
              </div>
            </el-upload>
            <h2 class="username">{{ userInfo.name || "未设置姓名" }}</h2>
            <div class="user-role">
              <el-tag :type="userInfo.role === '教师' ? 'success' : 'primary'">
                {{ userInfo.role }}
              </el-tag>
            </div>
            
            <!-- 积分展示部分 -->
            <div class="points-display">
              <div class="points-card">
                <el-tooltip content="当前积分" placement="top">
                  <div class="points-value">{{ userInfo.point || 0 }}</div>
                </el-tooltip>
                <div class="points-label">积分</div>
              </div>
              <el-button 
                type="primary" 
                text 
                @click="showPointsHistory"
                class="points-history-btn"
              >
                查看积分历史
              </el-button>
            </div>
            <!-- 积分展示部分结束 -->
          </div>

          <div class="user-actions">
            <el-button
              type="danger"
              @click="showLogoutConfirm"
              :icon="SwitchButton"
              size="large"
              style="width: 100%"
            >
              退出登录
            </el-button>
          </div>
        </el-card>
        
        <!-- 积分排行榜卡片 -->
        <el-card class="points-rank-card">
          <template #header>
            <div class="card-header">
              <span class="header-title">积分排行榜</span>
              <el-button type="primary" text @click="refreshPointsRank">刷新</el-button>
            </div>
          </template>
          <div v-loading="loadingRank">
            <div v-if="pointsRank.length === 0" class="empty-rank">
              暂无排行数据
            </div>
            <ul class="rank-list" v-else>
              <li v-for="(user, index) in pointsRank" :key="user.id" class="rank-item">
                <div class="rank-number" :class="{'top-rank': index < 3}">{{ index + 1 }}</div>
                <div class="rank-name">{{ user.name }}</div>
                <div class="rank-points">{{ user.point }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="18">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span class="header-title">个人信息</span>
              <div>
                <el-button
                  type="primary"
                  :icon="Edit"
                  @click="editMode = !editMode"
                  v-if="!editMode"
                >
                  编辑资料
                </el-button>

                <el-button
                  type="success"
                  :icon="Check"
                  @click="saveUserInfo"
                  v-if="editMode"
                  :loading="isSaving"
                >
                  保存
                </el-button>
                <el-button
                  type="info"
                  :icon="Close"
                  @click="cancelEdit"
                  v-if="editMode"
                >
                  取消
                </el-button>
              </div>
            </div>
          </template>

          <el-form
            :model="userInfo"
            label-width="120px"
            class="user-form"
            label-position="left"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" class="form-item">
                  <el-input v-model="userInfo.email" readonly>
                    <template #prefix>
                      <el-icon><Message /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="角色" class="form-item">
                  <el-input v-model="userInfo.role" readonly>
                    <template #prefix>
                      <el-icon><User /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学号" class="form-item" required>
                  <el-input
                    v-model="userInfo.number"
                    :disabled="!editMode"
                    placeholder="请输入学号"
                  >
                    <template #prefix>
                      <el-icon><Ticket /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" class="form-item" required>
                  <el-input
                    v-model="userInfo.name"
                    :disabled="!editMode"
                    placeholder="请输入姓名"
                  >
                    <template #prefix>
                      <el-icon><UserFilled /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学院" class="form-item">
                  <el-input
                    v-model="userInfo.department"
                    :disabled="!editMode"
                    placeholder="请输入学院"
                  >
                    <template #prefix>
                      <el-icon><School /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="班级" class="form-item">
                  <el-input
                    v-model="userInfo.className"
                    :disabled="!editMode"
                    placeholder="请输入班级"
                  >
                    <template #prefix>
                      <el-icon><Collection /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="班级ID" class="form-item">
                  <el-input v-model="userInfo.classId" readonly>
                    <template #prefix>
                      <el-icon><DocumentCopy /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="积分" class="form-item">
                  <el-input v-model="userInfo.point" readonly>
                    <template #prefix>
                      <el-icon><Medal /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        
        <!-- 积分历史卡片 -->
        <el-card class="points-history-card" v-if="showHistory">
          <template #header>
            <div class="card-header">
              <span class="header-title">积分历史记录</span>
              <el-button type="primary" text @click="refreshPointsHistory">刷新</el-button>
            </div>
          </template>
          <div v-loading="loadingHistory">
            <div v-if="pointsHistory.length === 0" class="empty-history">
              暂无积分记录
            </div>
            <el-table v-else :data="pointsHistory" style="width: 100%">
              <el-table-column prop="date" label="时间" width="180" />
              <el-table-column prop="description" label="获取方式" />
              <el-table-column prop="points" label="积分变化">
                <template #default="scope">
                  <span :class="scope.row.points > 0 ? 'points-increase' : 'points-decrease'">
                    {{ scope.row.points > 0 ? '+' : '' }}{{ scope.row.points }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalRecords"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../store/user'
import request from '../utils/request'
import { useRouter } from 'vue-router'
import { 
  Edit, 
  Check, 
  Close, 
  UserFilled, 
  Message, 
  User, 
  Ticket, 
  School, 
  Collection, 
  DocumentCopy, 
  EditPen, 
  SwitchButton,
  Medal
} from '@element-plus/icons-vue'

const router = useRouter();
const userStore = useUserStore();
const editMode = ref(false);
const isSaving = ref(false);
const isUploading = ref(false);
const uploadProgress = ref(0);
const defaultAvatar = computed(
  () => "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);
const originalUserInfo = ref({});
const avatarUrl = ref(defaultAvatar.value);

// 积分相关状态
const showHistory = ref(false);
const loadingHistory = ref(false);
const loadingRank = ref(false);
const pointsHistory = ref([]);
const pointsRank = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

const userInfo = ref({
  id: 0,
  email: "",
  role: "",
  number: "",
  name: "",
  department: "",
  className: "",
  classId: 0,
  avatar: "",
  point: 0, // 添加积分字段
});

onMounted(async () => {
  await fetchUserInfo();
  // 无论如何都尝试获取一次头像
  console.log("组件挂载完成，尝试直接获取头像");
  try {
    const url = await getAvatarUrl();
    console.log("直接获取头像结果:", url);
    avatarUrl.value = url;
  } catch (error) {
    console.error("直接获取头像失败:", error);
  }
  
  // 获取积分排行榜
  await fetchPointsRank();
});

async function fetchUserInfo() {
  try {
    console.log("开始获取用户信息...");
    const response = await request("/user/getUserInfo");
    const data = response.data || response;
    console.log("后端返回的用户信息：", data);
    console.log("用户头像字段(pic)：", data.pic);

    if (data.pic) {
      console.log("发现用户头像，正在获取...");
      const newAvatarUrl = await getAvatarUrl();
      console.log("获取到头像URL：", newAvatarUrl);
      avatarUrl.value = newAvatarUrl;
    } else {
      console.log("用户没有头像，使用默认头像");
      avatarUrl.value = defaultAvatar.value;
    }

    userInfo.value = {
      id: data.id,
      email: data.email,
      role: data.role === 1 ? "教师" : "学生",
      number: data.number || "",
      name: data.name || "",
      department: data.department || "",
      className: data.className || "",
      classId: data.classId || 0,
      avatar: avatarUrl.value,
      point: data.point || 0, // 从API获取积分
    };

    console.log("用户信息处理完成, 头像URL:", avatarUrl.value);
    originalUserInfo.value = JSON.parse(JSON.stringify(userInfo.value));
    userStore.setUserInfo(data);
  } catch (error: any) {
    console.error("获取用户信息失败:", error);
    ElMessage.error(error.message || "获取用户信息失败");
    avatarUrl.value = defaultAvatar.value;
  }
}

// 获取头像URL的方法
async function getAvatarUrl() {
  try {
    console.log("开始请求头像...");
    const response = await fetch('/api/user/download', {
      headers: {
        'Authorization': userStore.token || ''
      }
    });
    console.log("头像请求响应状态:", response.status);
    
    if (!response.ok) throw new Error('获取头像失败');
    
    const blob = await response.blob();
    console.log("获取到头像blob大小:", blob.size, "类型:", blob.type);
    
    const url = URL.createObjectURL(blob);
    console.log("生成的blob图片URL:", url);
    
    return url;
  } catch (error) {
    console.error('获取头像失败:', error);
    return defaultAvatar.value;
  }
}

function cancelEdit() {
  // 恢复原始数据
  userInfo.value = JSON.parse(JSON.stringify(originalUserInfo.value));
  editMode.value = false;
}

function beforeAvatarUpload(file: File) {
  const isValidFormat =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/gif";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isValidFormat) {
    ElMessage.error("头像只能是 JPG/PNG/GIF 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }

  // 开始上传，显示进度
  isUploading.value = true;
  uploadProgress.value = 0;

  return true;
}

function handleAvatarProgress(event: any) {
  uploadProgress.value = Math.round(event.percent);
}

function handleAvatarSuccess(res: any) {
  isUploading.value = false;
  if (res.code === 0) {
    getAvatarUrl().then(url => {
      avatarUrl.value = url;
      ElMessage.success('头像上传成功');
      const updatedUserInfo = userStore.userInfo || {};
      userStore.setUserInfo({
        ...updatedUserInfo,
        pic: res.data.url
      } as any);
    });
  } else {
    ElMessage.error(res.msg || '头像上传失败');
  }
}

function handleAvatarError(err: any) {
  isUploading.value = false;
  ElMessage.error("头像上传失败，请稍后重试");
  console.error("头像上传失败:", err);
}

async function saveUserInfo() {
  // 表单验证
  if (!userInfo.value.name) {
    ElMessage.warning("请填写姓名");
    return;
  }

  isSaving.value = true;

  try {
    await request("/user/updateUserInfo", {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        number: userInfo.value.number,
        name: userInfo.value.name,
        department: userInfo.value.department,
        className: userInfo.value.className,
        classId: userInfo.value.classId,
      }),
    });

    ElMessage.success("用户信息更新成功");
    editMode.value = false;

    // 保存成功后刷新用户信息
    await fetchUserInfo();
  } catch (error: any) {
    ElMessage.error(error.message || "更新用户信息失败");
  } finally {
    isSaving.value = false;
  }
}

function showLogoutConfirm() {
  ElMessageBox.confirm("确定要退出登录吗？", "退出提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      logout();
    })
    .catch(() => {
      // 用户取消操作
    });
}

async function logout() {
  try {
    await request("/user/logout", {
      method: "POST",
    });
    userStore.logout();
    ElMessage.success("退出登录成功");
    router.push("/");
  } catch (error: any) {
    ElMessage.error(error.message || "退出登录失败");
  }
}

// 积分相关功能
function showPointsHistory() {
  showHistory.value = !showHistory.value;
  if (showHistory.value) {
    fetchPointsHistory();
  }
}

async function fetchPointsHistory() {
  loadingHistory.value = true;
  try {
    // 这里应该调用API获取积分历史
    // 由于API文档中没有直接的积分历史API，这里模拟数据
    // 实际开发时应替换为真实API
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟数据
    pointsHistory.value = [
      { date: '2023-05-20 14:30', description: '完成题目: 两数之和', points: 10 },
      { date: '2023-05-18 16:45', description: '每日签到', points: 5 },
      { date: '2023-05-15 09:20', description: '参与讨论', points: 3 },
      { date: '2023-05-10 11:35', description: '完成题目: 打家劫舍', points: 15 },
      { date: '2023-05-05 10:25', description: '每日签到', points: 5 },
    ];
    
    totalRecords.value = 20; // 模拟总记录数
  } catch (error: any) {
    console.error('获取积分历史失败:', error);
    ElMessage.error(error.message || '获取积分历史失败');
  } finally {
    loadingHistory.value = false;
  }
}

async function fetchPointsRank() {
  loadingRank.value = true;
  try {
    // 这里应该调用API获取积分排行
    // 由于API文档中没有直接的积分排行API，这里模拟数据
    // 实际开发时应替换为真实API
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟数据
    pointsRank.value = [
      { id: 1, name: '张三', point: 520 },
      { id: 2, name: '李四', point: 485 },
      { id: 3, name: '王五', point: 450 },
      { id: 4, name: '赵六', point: 390 },
      { id: 5, name: '钱七', point: 320 },
    ];
  } catch (error: any) {
    console.error('获取积分排行失败:', error);
    ElMessage.error(error.message || '获取积分排行失败');
  } finally {
    loadingRank.value = false;
  }
}

function refreshPointsHistory() {
  fetchPointsHistory();
}

function refreshPointsRank() {
  fetchPointsRank();
}

function handleSizeChange(val: number) {
  pageSize.value = val;
  fetchPointsHistory();
}

function handleCurrentChange(val: number) {
  currentPage.value = val;
  fetchPointsHistory();
}

let oldBlobUrl = '';
watch(avatarUrl, (newUrl, oldUrl) => {
  if (oldUrl && oldUrl !== defaultAvatar.value) {
    URL.revokeObjectURL(oldUrl);
  }
  oldBlobUrl = newUrl;
});

onUnmounted(() => {
  if (oldBlobUrl && oldBlobUrl !== defaultAvatar.value) {
    URL.revokeObjectURL(oldBlobUrl);
  }
});
</script>

<style scoped>
.personal-space {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.avatar-card,
.info-card,
.points-history-card,
.points-rank-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  transition: all 0.3s;
}

.avatar-card:hover,
.info-card:hover,
.points-history-card:hover,
.points-rank-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 15px;
}

.user-avatar {
  transition: all 0.3s;
  border: 3px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.upload-progress {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.username {
  margin: 15px 0 5px;
  font-size: 1.4rem;
  font-weight: 500;
}

.user-role {
  margin-bottom: 15px;
}

.user-actions {
  margin-top: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.form-item {
  margin-bottom: 15px;
}

.user-form {
  padding: 10px;
}

@media (max-width: 768px) {
  .personal-space {
    padding: 10px;
  }
}

/* 积分相关样式 */
.points-display {
  margin: 15px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.points-card {
  background: linear-gradient(45deg, #4285f4, #34a853);
  color: white;
  padding: 15px 25px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  width: 80%;
  margin-bottom: 10px;
}

.points-value {
  font-size: 2.2rem;
  font-weight: bold;
  margin-bottom: 5px;
}

.points-label {
  font-size: 1rem;
  opacity: 0.9;
}

.points-history-btn {
  margin-top: 8px;
}

.rank-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.rank-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.rank-item:last-child {
  border-bottom: none;
}

.rank-number {
  font-weight: bold;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f5f7fa;
  margin-right: 15px;
}

.top-rank {
  color: white;
}

.rank-item:nth-child(1) .top-rank {
  background-color: #f5c518; /* 金牌 */
}

.rank-item:nth-child(2) .top-rank {
  background-color: #c0c0c0; /* 银牌 */
}

.rank-item:nth-child(3) .top-rank {
  background-color: #cd7f32; /* 铜牌 */
}

.rank-name {
  flex: 1;
}

.rank-points {
  font-weight: bold;
  color: #4285f4;
}

.empty-rank, .empty-history {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.points-increase {
  color: #67c23a;
  font-weight: bold;
}

.points-decrease {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
